package com.yiwei.zxp.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.yiwei.zxp.Application;
import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.LoginBean;
import com.yiwei.zxp.api.bean.QuickLoginBean;
import com.yiwei.zxp.api.bean.SmsSendBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.fragment.LoginPassFragment;
import com.yiwei.zxp.fragment.LoginPhoneFragment;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.MD5;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.PreferenceUtils;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.BottomIconText;
import com.yiwei.zxp.view.CustomViewPager;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class LoginNewActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.pager)
    CustomViewPager pager;
    @BindView(R.id.btn_wechat)
    BottomIconText btnWechat;
    @BindView(R.id.txt_agree)
    TextView txtAgree;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    private Unbinder unbiner;
    private boolean isFromInvite;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_new);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        isFromInvite = getIntent().getBooleanExtra("is_from_invite", false);
        UI.setTvHtml(txtAgree, R.string.login_agree);
        Fragment[] fragments = new Fragment[]{new LoginPassFragment(), new LoginPhoneFragment()};
        String[] titles = new String[]{"账号密码登录", "手机号码登录"};
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });
        tablayout.setupWithViewPager(pager);
    }


    public void getLogin(String username, String password) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        LoginBean bean = new LoginBean();
        bean.username = username;
        bean.password = MD5.getMD5str(password);
        Api.api_service.getLogin(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Set<String> tagSet = new LinkedHashSet<String>();
                    // tagSet.add(model.getData().getUser_name());
                    tagSet.add(result.datas.mobile);
                    JPushInterface.setAliasAndTags(getApplicationContext(), result.datas.mobile + "", tagSet, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {
                            //  Log.i("", i + s + "       " + set.toString());
//                                ToastUtil.makeText(getApplicationContext(), i+"   "+s+"     "+set.toString(), Toast.LENGTH_SHORT).show();
                            switch (i) {
                                case 0:
                                    Log.i("", i + s + "       " + set.toString());
                                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                                    break;
                                case 6002:
                                    Log.i("6002", "60002");
                                    // 延迟 60 秒来调用 Handler 设置别名
                                    break;
                                default:
                                    Log.i("6002", "default");
                            }
                        }

                    });
                    UserInfoGlobal.saveLoginInfo(result.datas);
                    if (isFromInvite) {
                        ToastUtil.makeText(this, "登录成功");
                        finish();
                    } else {
                        ToastUtil.makeText(this, "登录成功");
                        Util.startActivity(this, BussinessMainActivity.class);
                        finish();
                    }

                });
    }

    public void getSmsSend(String phone) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        SmsSendBean bean = new SmsSendBean();
        bean.phone = phone;
        Api.api_service.getForgetSend(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Intent intent = new Intent(this, LoginPhoneActivity.class);
                    intent.putExtra("phone", phone);
                    startActivity(intent);
                    finish();
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                });
    }

    private void setPlat(String name) {
        Platform weibo = ShareSDK.getPlatform(name);
        if (weibo.isAuthValid()) {
            weibo.removeAccount(true);
//            PlatformDb platDB = weibo.getDb();
//            ((LoginActivity) getActivity()).getQuickLogin(platDB.getUserId(), name);
//            return;
        }


//回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        weibo.SSOSetting(false);
        weibo.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub

                arg2.printStackTrace();
//                ToastUtil.makeText(getActivity(), arg2.toString());
            }

            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
//                        platform.getDb().exportData();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        Log.i("dasdadsasda", "action=" + action);
                        if (action == Platform.ACTION_USER_INFOR) {
                            PlatformDb platDB = platform.getDb();//获取数平台数据DB
                            //通过DB获取各种数据
//                            ToastUtil.makeText(getActivity(), "token" + platDB.getToken() + "\ngender=" + platDB.getUserGender() + "\nicon=" + platDB.getUserIcon() + "\nid=" + platDB.getUserId() + "\nname=" + platDB.getUserName());

                            getQuickLogin(platDB.getUserId(), name);
//                            Log.i("dasdadsasda", "token" + platDB.getToken() + "\ngender=" + platDB.getUserGender() + "\nicon=" + platDB.getUserIcon() + "\nid=" + platDB.getUserId() + "\nname=" + platDB.getUserName());
//                            platDB.getToken();
//                            platDB.getUserGender();
//                            platDB.getUserIcon();
//                            platDB.getUserId();
//                            platDB.getUserName();
                        }
                    }
                });


            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        weibo.authorize();
        weibo.showUser(null);//执行登录，登录后在回调里面获取用户资料
    }

    public void getQuickLogin(String tp_id, String plat) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        QuickLoginBean item = new QuickLoginBean();
        item.tp_id = tp_id;
        item.tp_type = getPlatName(plat);
        Api.api_service.getQuickLogin(item).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        Intent intent = new Intent(this, WechatLoginActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    } else if (result.code.equals("01")) {
                        Intent intent = new Intent(this, WechatBindActivity.class);
                        intent.putExtra("tp_id", tp_id);
                        intent.putExtra("plat", getPlatName(plat));
                        startActivity(intent);
                        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    } else {
                        ToastUtil.makeText(this, result.msg);
                    }
                });
    }

    public String getPlatName(String plat) {
        if (plat.equals(QQ.NAME)) {
            return Const.QuickLogin.QQ;
        } else if (plat.equals(Wechat.NAME)) {
            return Const.QuickLogin.WECHAT;
        } else if (plat.equals(SinaWeibo.NAME)) {
            return Const.QuickLogin.WEIBO;
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.txt_right, R.id.btn_wechat, R.id.txt_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                Util.startActivity(this, WechatChatActivity.class);
                break;
            case R.id.btn_wechat:
                ToastUtil.makeText(this, "敬请期待");
//                setPlat(Wechat.NAME);
                break;
            case R.id.txt_agree:
                Intent intent = new Intent(this, WebTextActivity.class);
                intent.putExtra("contract_id", Const.Contract.REGISTER);
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }
}
